<html>
  <head>
    <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title> MyBatis_3	连接池、事务控制、动态SQL | 清汤牛肉锅</title>
<meta name="description" content="温故而知新
" />
<link rel="shortcut icon" href="https://ArtZoick.github.io//favicon.ico?v=1572228390311">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.10.0/katex.min.css">
<link rel="stylesheet" href="https://ArtZoick.github.io//styles/main.css">

<script src="https://cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700">


<script async src="https://www.googletagmanager.com/gtag/js?id=UA-143265163-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-143265163-1');
</script>


  </head>
  <body>
    <div class="main">
      <div class="main-content">
        <div class="site-header">
  <a href="https://ArtZoick.github.io/">
  <img class="avatar" src="https://ArtZoick.github.io//images/avatar.png?v=1572228390311" alt="">
  </a>
  <h1 class="site-title">
    清汤牛肉锅
  </h1>
  <p class="site-description">
    温故而知新

  </p>
  <div class="menu-container">
    
      
        <a href="/" class="menu">
          首页
        </a>
      
    
      
        <a href="/archives" class="menu">
          归档
        </a>
      
    
      
        <a href="/tags" class="menu">
          标签
        </a>
      
    
      
        <a href="/post/about" class="menu">
          关于
        </a>
      
    
      
        <a href="/post/beef" class="menu">
          牛肉锅
        </a>
      
    
  </div>
  <div class="social-container">
    
      
    
      
    
      
    
      
    
      
    
  </div>
</div>

        <div class="post-detail">
          <article class="post">
            <h2 class="post-title">
               MyBatis_3	连接池、事务控制、动态SQL
            </h2>
            <div class="post-info">
              <span>
                2019-07-03
              </span>
              <span>
                5 min read
              </span>
              
                <a href="https://ArtZoick.github.io//tag/framework" class="post-tag">
                  # 框架
                </a>
              
                <a href="https://ArtZoick.github.io//tag/MyBatis" class="post-tag">
                  # MyBatis
                </a>
              
            </div>
            
            <div class="post-content-wrapper">
              <div class="post-content">
                <h2 id="连接池">连接池</h2>
<p><strong>１、连接池：</strong><br>
　　　　在实际开发中都会使用连接池<br>
　　　　因为它可以减少我们获取连接所消耗的时间</p>
<p><strong>２、mybatis中的连接池：</strong><br>
　　　　mybatis连接池提供了3种配置方式：<br>
　　　　配置的位置：<br>
　　　　　　主配置文件SqlMapConfig.xml中的dataSource标签，type属性就是表示采用何种连接池方式。<br>
　　　　type属性的值：<br>
　　　　　　<em><strong>POOLED</strong></em>　　采用传统的javax.sql.DataSource规范中的连接池，mybatis中有针对规范的实现<br>
　　　　　　<em><strong>UNPOOLED</strong></em>　采用传统的获取连接的方式，虽然也实现javax.sql.DataSource接口，但是并没有使用池的思想<br>
　　　　　　<em><strong>JNDI</strong></em>　　　采用服务器提供的JNDI技术实现，来获取DataSource对象，不同的服务器所能拿到DataSource是不一样的<br>
　　　　注意：如果不是web或者maven的war工程，是不能使用的<br>
　　　　　　学习时使用的时tomcat服务器，采用的连接池就是dbcp连接池</p>
<h2 id="mybatis中的事务">MyBatis中的事务</h2>
<p>什么是事务<br>
　　事务的四大特性ACID<br>
　　不考虑隔离性会产生的3个问题<br>
　　解决办法：四种隔离级别</p>
<p>它是通过sqlsession对象的commit方法和rollback方法实现事务的提交和回滚</p>
<h2 id="动态sql">动态SQL</h2>
<h3 id="if标签的使用">if标签的使用</h3>
<h4 id="1接口中定义">1.接口中定义</h4>
<pre><code class="language-java"> List&lt;User&gt; findByCondition(User user);
</code></pre>
<h4 id="2mapper中定义">2.mapper中定义</h4>
<pre><code class="language-xml">&lt;select id=&quot;findByCondition&quot; resultMap=&quot;userMap&quot; parameterType=&quot;user&quot;&gt;
        select * from user where 1=1
        &lt;if test=&quot;userName != null&quot;&gt;
            and username = #{userName}
        &lt;/if&gt;
        &lt;if test=&quot;userSex != null&quot;&gt;
            and sex = #{userSex}
        &lt;/if&gt;    
&lt;/select&gt;
</code></pre>
<p>其中： <if test="userName != null">这条语句中，userName值得是实体类中的属性名， and username = #{userName}这里是将实体类的userName传给数据库的username</p>
<h3 id="3测试类中测试">3.测试类中测试</h3>
<pre><code class="language-java">/**
     * 测试findByCondition
     * @throws IOException
     */
    @Test
    public void testFindByCondiion() throws Exception {
        User u = new User();
        u.setUserName(&quot;zoick&quot;);
//        u.setUserSex(&quot;女&quot;);
        init();
        //5.使用代理对象执行方法
        List&lt;User&gt; users = userDao.findByCondition(u);
        for (User user : users) {
            System.out.println(user);
        }
    }

</code></pre>
<h2 id="where和foreach标签的使用">where和foreach标签的使用</h2>
<p>用于多个查询的sql<br>
select * from user where id in(41,42,45)<br>
通过一个类中传入集合的方法<br>
QueryVo类</p>
<pre><code class="language-java">@Getter
@Setter
public class QueryVo {

    private User user;
    private List&lt;Integer&gt; ids;
}

</code></pre>
<h3 id="1接口中定义-2">1.接口中定义</h3>
<pre><code class="language-java">    /**
     * 根据Queryvo中提供的id集合，查询用户信息
     * @param vo
     * @return
     */
    List&lt;User&gt; findUserInIds(QueryVo vo);
</code></pre>
<h3 id="2mapper中定义-2">2.mapper中定义</h3>
<pre><code class="language-xml">&lt;!--根据queryvo中Id集合实现查询用户列表--&gt;
    &lt;select id=&quot;findUserInIds&quot; resultMap=&quot;userMap&quot; parameterType=&quot;queryvo&quot;&gt;
        select * from user
        &lt;where&gt;
            &lt;if test=&quot;ids != null and ids.size()&gt;0&quot;&gt;
                &lt;foreach collection=&quot;ids&quot; open=&quot;and id in (&quot; close=&quot;)&quot; item=&quot;uuuuid&quot; separator=&quot;,&quot;&gt;
                    #{uuuuid}
                &lt;/foreach&gt;
            &lt;/if&gt;
        &lt;/where&gt;
    &lt;/select&gt;
</code></pre>
<p>注意if标签中的内容都是来源于parameterType参数</p>
<h3 id="3测试代码">3.测试代码</h3>
<pre><code class="language-java">/**
     * 测试foreach标签的使用
     *
     * @throws IOException
     */
    @Test
    public void testFindInIds () throws Exception {
        QueryVo vo = new QueryVo();
        List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();
        list.add(41);
        list.add(42);
        list.add(45);
        vo.setIds(list);
        init();
        //5.使用代理对象执行方法
        List&lt;User&gt; users = userDao.findUserInIds(vo);
        for (User user : users) {
            System.out.println(user);
        }
    }
</code></pre>
<h3 id="抽取重复的sql">抽取重复的sql</h3>
<h4 id="1定义">1.定义</h4>
<pre><code class="language-xml">&lt;!--抽取重复的sql语句--&gt;
    &lt;sql id=&quot;defaultUser&quot;&gt;
        select * from user
    &lt;/sql&gt;
</code></pre>
<h4 id="2使用">2.使用</h4>
<pre><code class="language-xml">&lt;include refid=&quot;defaultUser&quot;&gt;&lt;/include&gt;
</code></pre>
<pre><code class="language-xml"> &lt;!--抽取重复的sql语句--&gt;
    &lt;sql id=&quot;defaultUser&quot;&gt;
        select * from user
    &lt;/sql&gt;

    &lt;!--配置查询所有  其中id不能乱写必须是dao接口中的方法  resultType写的是实体类的全路径--&gt;
    &lt;select id=&quot;findAll&quot; resultMap=&quot;userMap&quot;&gt;
        &lt;include refid=&quot;defaultUser&quot;/&gt;
    &lt;/select&gt;
</code></pre>
<p><strong>注意：</strong> 尽量不要使用分号，sql语句可能会拼接</p>
<hr>

              </div>
              <div class="toc-container">
                <ul class="markdownIt-TOC">
<li>
<ul>
<li><a href="#%E8%BF%9E%E6%8E%A5%E6%B1%A0">连接池</a></li>
<li><a href="#mybatis%E4%B8%AD%E7%9A%84%E4%BA%8B%E5%8A%A1">MyBatis中的事务</a></li>
<li><a href="#%E5%8A%A8%E6%80%81sql">动态SQL</a>
<ul>
<li><a href="#if%E6%A0%87%E7%AD%BE%E7%9A%84%E4%BD%BF%E7%94%A8">if标签的使用</a>
<ul>
<li><a href="#1%E6%8E%A5%E5%8F%A3%E4%B8%AD%E5%AE%9A%E4%B9%89">1.接口中定义</a></li>
<li><a href="#2mapper%E4%B8%AD%E5%AE%9A%E4%B9%89">2.mapper中定义</a></li>
</ul>
</li>
<li><a href="#3%E6%B5%8B%E8%AF%95%E7%B1%BB%E4%B8%AD%E6%B5%8B%E8%AF%95">3.测试类中测试</a></li>
</ul>
</li>
<li><a href="#where%E5%92%8Cforeach%E6%A0%87%E7%AD%BE%E7%9A%84%E4%BD%BF%E7%94%A8">where和foreach标签的使用</a>
<ul>
<li><a href="#1%E6%8E%A5%E5%8F%A3%E4%B8%AD%E5%AE%9A%E4%B9%89-2">1.接口中定义</a></li>
<li><a href="#2mapper%E4%B8%AD%E5%AE%9A%E4%B9%89-2">2.mapper中定义</a></li>
<li><a href="#3%E6%B5%8B%E8%AF%95%E4%BB%A3%E7%A0%81">3.测试代码</a></li>
<li><a href="#%E6%8A%BD%E5%8F%96%E9%87%8D%E5%A4%8D%E7%9A%84sql">抽取重复的sql</a>
<ul>
<li><a href="#1%E5%AE%9A%E4%B9%89">1.定义</a></li>
<li><a href="#2%E4%BD%BF%E7%94%A8">2.使用</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

              </div>
            </div>
          </article>
        </div>

        
          <div class="next-post">
            <div class="next">下一篇</div>
            <a href="https://ArtZoick.github.io//post/MyBatis_2">
              <h3 class="post-title">
                MyBatis_2	基本的CRUD
              </h3>
            </a>
          </div>
        

        
          
            <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
<script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

<div id="gitalk-container"></div>

<script>

  var gitalk = new Gitalk({
    clientID: 'a2471d09bddb5be481ee',
    clientSecret: '05d427fb27f873cfabace27b9f042f2c7f23000f',
    repo: 'ArtZoick.github.io',
    owner: 'ArtZoick',
    admin: ['ArtZoick'],
    id: (location.pathname).substring(0, 49),      // Ensure uniqueness and length less than 50
    distractionFreeMode: false  // Facebook-like distraction free mode
  })

  gitalk.render('gitalk-container')

</script>

          

          
        

        <div class="site-footer">
  <a href="https://zhidao.baidu.com/question/1867120235416383707.html" target="_blank" onclick="alert('盲生，你发现了华点！');">学习强国</a>

<!--Tido对话插件-->
<script src="//code.tidio.co/5fh6jaqvluqj8jjuf5zlqrf5tlzpktnx.js"></script>
<style>
.text-popup {
    animation: textPopup 1s;
    color: red;
    user-select: none;
    white-space: nowrap;
    position: absolute;
    z-index: 99;
}
@keyframes textPopup {
    0%, 100% {
        opacity: 0;
    }
    5% {
        opacity: 1;
    }
    100% {
        transform: translateY(-50px);    
    }
}
</style>
<script type="text/javascript" src="https://cdn.bootcss.com/canvas-nest.js/1.0.1/canvas-nest.min.js">
!function(){function n(n,e,t){return n.getAttribute(e)||t}function e(n){return document.getElementsByTagName(n)}
function t(){var t=e("script"),o=t.length,i=t[o-1];return{l:o,z:n(i,"zIndex",-1),o:n(i,"opacity",.5),c:n(i,"color","0,0,0")
,n:n(i,"count",99)}}function o(){a=m.width=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidt
h,c=m.height=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight}function i(){r.clearRect
(0,0,a,c);var n,e,t,o,m,l;s.forEach(function(i,x){for(i.x+=i.xa,i.y+=i.ya,i.xa*=i.x>a||i.x<0?-1:1,i.ya*=i.y>c||i.y<0?-1:1,r.
fillRect(i.x-.5,i.y-.5,1,1),e=x+1;e<u.length;e++)n=u[e],null!==n.x&&null!==n.y&&(o=i.x-n.x,m=i.y-n.y,l=o*o+m*m,l<n.max&&(n===
y&&l>=n.max/2&&(i.x-=.03*o,i.y-=.03*m),t=(n.max-l)/n.max,r.beginPath(),r.lineWidth=t/2,r.strokeStyle="rgba("+d.c+","+(t+.2)+")
",r.moveTo(i.x,i.y),r.lineTo(n.x,n.y),r.stroke()))}),x(i)}var a,c,u,m=document.createElement("canvas"),d=t(),l="c_n"+d.l,r=m.
getContext("2d"),x=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.
oRequestAnimationFrame||window.msRequestAnimationFrame||function(n){window.setTimeout(n,1e3/45)},w=Math.random,y={x:null,y:nul
l,max:2e4};m.id=l,m.style.cssText="position:fixed;top:0;left:0;z-index:"+d.z+";opacity:"+d.o,e("body")[0].appendChild(m),o(),
window.οnresize=o,window.οnmοusemοve=function(n){n=n||window.event,y.x=n.clientX,y.y=n.clientY},window.οnmοuseοut=function(){y
.x=null,y.y=null};for(var s=[],f=0;d.n>f;f++){var h=w()*a,g=w()*c,v=2*w()-1,p=2*w()-1;s.push({x:h,y:g,xa:v,ya:p,max:6e3})}u=
s.concat([y]),setTimeout(function(){i()},100)}();
</script>

<!--鼠标点击-->
<!--富强-->
<script type="text/javascript"> 
/* 鼠标特效 */ 
var a_idx = 0; 
jQuery(document).ready(function($) { 
    $("body").click(function(e) { 
        var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正" ,"法治", "爱国", "敬业", "诚信", "友善"); 
        var $i = $("<span/>").text(a[a_idx]); 
        a_idx = (a_idx + 1) % a.length; 
        var x = e.pageX, 
        y = e.pageY; 
        $i.css({ 
            "z-index": 999, 
            "top": y - 20, 
            "left": x, 
            "position": "absolute", 
            "font-weight": "bold", 
            "color": "#ff6651" 
        }); 
        $("body").append($i); 
        $i.animate({ 
            "top": y - 180, 
            "opacity": 0 
        }, 
        1500, 
        function() { 
            $i.remove(); 
        }); 
    }); 
}); 
</script>
<!--edn--富强--> | 
  <a class="rss" href="https://ArtZoick.github.io//atom.xml" target="_blank">RSS</a>
</div>

<script>
  hljs.initHighlightingOnLoad()

  let mainNavLinks = document.querySelectorAll(".markdownIt-TOC a");

  // This should probably be throttled.
  // Especially because it triggers during smooth scrolling.
  // https://lodash.com/docs/4.17.10#throttle
  // You could do like...
  // window.addEventListener("scroll", () => {
  //    _.throttle(doThatStuff, 100);
  // });
  // Only not doing it here to keep this Pen dependency-free.

  window.addEventListener("scroll", event => {
    let fromTop = window.scrollY;

    mainNavLinks.forEach((link, index) => {
      let section = document.getElementById(decodeURI(link.hash).substring(1));
      let nextSection = null
      if (mainNavLinks[index + 1]) {
        nextSection = document.getElementById(decodeURI(mainNavLinks[index + 1].hash).substring(1));
      }
      console.log('section.offsetHeight', section.offsetHeight);
      if (section.offsetTop <= fromTop) {
        if (nextSection) {
          if (nextSection.offsetTop > fromTop) {
            link.classList.add("current");
          } else {
            link.classList.remove("current");    
          }
        } else {
          link.classList.add("current");
        }
      } else {
        link.classList.remove("current");
      }
    });
  });

</script>

      </div>
    </div>
  </body>
</html>
